package optional;

import java.util.Optional;

class Car {
    private String brand;
    private String color;

    public Car() {
    }

    public Car(String brand, String color) {
        this.brand = brand;
        this.color = color;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

class Person {

    private String name;
    private String gender;
    private int age;
    private Car car;

    public Person() {
    }

    public Person(String name, String gender, int age, Car car) {
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.car = car;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    public String introduce() {
        return "hello,my name is:" + this.name + ",I am " + this.age + " years old!";
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                '}';
    }


}

public class OptionalDemo {

    /*
    public static void sayHello(Person p){
        if(p!=null){
            System.out.println(p.introduce());
        }else{
            System.out.println("unknown");
        }
    }*/

    public static void sayHello(Person p) {
        Optional<Person> person = Optional.ofNullable(p);
        //写法一：
        //System.out.println(person.map(per -> per.introduce()).orElse("unknown"));
        //写法二：
        System.out.println(person.map(Person::introduce).orElse("unknown"));
    }

    public static String getCarBrand(Person p) throws Exception{
        Optional<Person> person = Optional.ofNullable(p);
        return person.map(Person::getCar).map(Car::getBrand).orElseThrow(()->new Exception("Person or Car is null!"));
        //或者下面的写法
        //return person.map(per->per.getCar()).map(c->c.getBrand()).orElseThrow(()->new Exception("Person or Car is null!"));
    }

    public static void main(String[] args) throws Exception {
        //Person p = new Person("张三","男",30,new Car("BMW","red"));
        Person p = null;
        sayHello(p);
        System.out.println(getCarBrand(p));
    }
}
